<?php

namespace app\common\service;

use ba\Random;

class DouBaoVocalService extends ApiService
{

    private $accessToken;
    private $appId;
    private $apiUrl;


    public function __construct()
    {
        $this->accessToken = env('DOUBAO.TTS_ACCESS_TOKEN', '');
        $this->appId = env('DOUBAO.TTS_APP_ID', '');
        // $this->endpointId = env('DOUBAO.DEEPSEEK_3_1_ENDPOINT_ID', '');
        $this->apiUrl = 'https://openspeech.bytedance.com/api/v1/tts';
    }


    public function llmTts(string $word, int|float $speedRatio = null)
    {
        $uid = Random::uuid();
        $param = [
            'app' => [
                "appid" => $this->appId,
                "token" => $this->accessToken,
                "cluster" => "volcano_tts",
            ],
            "user" => [
                "uid" => $this->appId
            ],
            "audio" => [
                "voice_type" => "zh_female_qingxinnvsheng_mars_bigtts",
                "encoding" => "mp3",
                "speed_ratio" => $speedRatio ?? 1.0,
            ],
            'request' => [
                "reqid" => $uid,
                "text" => $word,
                'operation' => 'query'
            ]
        ];
        $header = [
            'Authorization: Bearer; ' . $this->accessToken,
        ];
        $res = HttpService::postJson($this->apiUrl, $param, $header);
        if (!$res) {
            $this->setError('语音合成生成失败');
            return false;
        }
        $res = json_decode($res, true);
        if (isset($res['code']) && $res['code'] != 3000) {
            $this->setError('语音合成生成失败;错误码：' . $res['code']);
            return false;
        }
        return base64_decode($res['data']);

    }
}